package com.example.gmwang.washapplication.utils;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.gmwang.washapplication.R;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;


/**
 * Created by WZ on 2017/8/1.
 */

public class BaseActivity extends FragmentActivity {
    private InputMethodManager manager;//键盘管理器
    private Dialog baseProgressDialog;//基类的等待loading
    private static Context baseContext;
    private static final Charset UTF8 = Charset.forName("UTF-8");
    public static String mxRsttext;


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseContext = BaseActivity.this;
        Log.e("asdasdasd", Build.VERSION.RELEASE);
        Window window = getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(getResources().getColor(R.color.colorAccent));
        }
        ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
            ViewCompat.setFitsSystemWindows(mChildView, true);
        }
       /* Interceptor appInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                String s = request.body().toString();
                Log.e("拦截器", s);
                Response response = null;
                response = chain.proceed(request);
                return response;
            }
        };*/
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new TokenInterceptor())
//                .addInterceptor(new LogInterceptor())
                .cache(new Cache(new File(
                        this.getCacheDir().getAbsolutePath() + File.separator + "data" + "/okhttpCache"), 10 * 1024 * 102))
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();


        OkHttpUtils.initClient(client);


    }

    /**
     * 界面初始化+监听
     */
    public void init() {

    }

    /**
     * @return
     */
    public static Context getmContext() {
        return baseContext;
    }

    /**
     * 隐藏等待框
     */
    public void dismissProgressDialog() {
        if (baseProgressDialog != null) {
            baseProgressDialog.dismiss();
        }
    }


    /**
     * 键盘是否主动弹出
     */
    public void getKeyboard(final EditText ed) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                manager = (InputMethodManager) ed.getContext().getSystemService(Context
                        .INPUT_METHOD_SERVICE);
                manager.showSoftInput(ed, 0);
            }
        }, 500);
    }

    // 点击空白区域 自动隐藏软键盘
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }


    /**
     * 非空校验
     */
    protected boolean isEmpty(Object o) {
        if (null == o) {
            return true;
        }
        if (o instanceof TextView) {
            return TextUtils.isEmpty(((TextView) o).getText().toString().trim());
        } else if (o instanceof Spinner) {
            return ((Spinner) o).getAdapter().isEmpty() || TextUtils.isEmpty(((Spinner) o)
                    .getSelectedItem().toString().trim());
        } else if (o instanceof String) {
            return TextUtils.isEmpty((CharSequence) o);
        }
        return true;
    }

    /**
     * 全局自动刷新Token的拦截器
     * <p>
     * 作者：余天然 on 16/9/5 下午3:31
     */
    public class TokenInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();

            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            String bodyString = buffer.clone().readString(charset);
            Log.e("拦截器", bodyString);

            return response;
        }
    }


    // 使app字体不受系统的字体的影响
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    //获取版本号
    public String getVersionName() {
        // 获取packagemanager的实例
        PackageManager packageManager = getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }
}
